import React, {Component, Fragment} from 'react';
import TodoItem from './TodoItem';
import './index.css';

class TodoList extends Component {
  constructor(props) {
    super(props);

    this.state = {
      inputVal: '',
      list: ['react', 'react-dom']
    }

    this.handInputChange = this.handInputChange.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleItemDelete = this.handleItemDelete.bind(this);
  }

  render() {
    return (
      <Fragment>
        <label htmlFor="inputArea">填写代办任务：</label>
        <input id="inputArea" className="inputBorder" value={this.state.inputVal} onChange={this.handInputChange}/>
        <button onClick={this.handleBtnClick}>提交</button>
        <div>
          {this.getTodoItem()}
        </div>
      </Fragment>
    );
  }

  getTodoItem() {
    return this.state.list.map((item, index) => {
      return (<TodoItem key={index} content={item} index={index} handleClick={this.handleItemDelete} />)
    });
  }

  handInputChange(e) {
    const inputVal = e.target.value;
    this.setState(() => (
      {
        inputVal: inputVal
      }
    ));
  }

  handleBtnClick() {
    this.setState((prevState) => (
      {
        list: [...prevState.list, prevState.inputVal],
        inputVal: ''
      }
    ));
  }

  handleItemDelete(index) {
    this.setState((prevState) => {
      const list = [...prevState.list];
      list.splice(index, 1);
      return {
        list
      }
    });
  }

}

export default TodoList;
